/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function(head, k) {
  if(!head) return null;
  if(!head.next) return head;
  let length = 0, temp = head;
  while(temp) {
    length++;
    temp = temp.next;
  }
  let count = length;
  k %= length;
  if(k == 0) return head;
  temp = head;
  while(temp) {
    temp = temp.next;
    count--;
    if(count == k) break;
  }
  let newHead = temp;
  while(temp.next) {
    temp = temp.next;
  }
  temp.next = head;
  while(temp.next != newHead) {
    temp = temp.next;
  }
  temp.next = null;
  return newHead;
};
